﻿

/**
* 基础
*/
var global = (function () {
    return {
        //localUrl: "http://192.168.3.137:8080/", //测试地址
        //localUrl: "http://192.168.3.30:8080/", //测试地址
        localUrl: "http://h5.pushunjinfuchina.com/", //线上地址
        //localUrl: "http://60.205.216.249:8080/",  //测试
        //moXieApiKey:"36a9272aebb141949c004d08b7d69f21",//线上key

        netError: "请求数据失败，请检测网络",
        serverError: "服务器繁忙，请稍后重试",
        paramError: "信息丢失，请稍后重试",
        loginTimeout: "未登录或登录超时，请重新登录",

        query: (function () {
            var re = {};
            var que = window.location.search.substr(1);
            if (que) {
                var arr = que.split("&");
                for (var i = 0; i < arr.length; i++) {
                    var num = arr[i].indexOf("=");
                    if (num > 0) {
                        re[arr[i].substring(0, num)] = decodeURIComponent(arr[i].substr(num + 1));
                    }
                }
                return re;
            }
            return null;
        })(),
        storage: {
            get: function (key) {
                return localStorage.getItem(key);
            },
            set: function (key, value) {
                localStorage.setItem(key, value);
            },
            clear: function (key) {
                localStorage.removeItem(key);
            }
        },
        cache: {
            get: function (key) {
                return sessionStorage.getItem(key);
            },
            set: function (key, value) {
                sessionStorage.setItem(key, value);
            },
            clear: function (key) {
                sessionStorage.removeItem(key);
            }
        }
    }
})();


/**
* 数据
*/
var dataUtil = (function () {
    return {
        //姓名验证
        isName: function (text) { if (!/^[\u4e00-\u9fa5]{2,20}$/i.test(text)) { global.log("IsName Error", "输入姓名" + text) } return /^[\u4e00-\u9fa5]{2,20}$/i.test(text); },
        //数字验证
        isNumber: function (text) { return /^[1-9][0-9]*$/i.test(text); },
        //手机验证
        isMobile: function (text) { return /^[1][345789][0-9]{9}$/i.test(text); },
        //邮箱验证
        isEmail: function (text) { return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/i.test(text); },
        //金钱格式验证
        isMoney: function (text) { return /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/i.test(text); },
        //去除空格
        removeBlank: function (v) { return v.replace(/\s/g, ""); },
        //json转string
        jsonToString: function (v) { return JSON.stringify(v) },
        //string转json
        stringToJson: function (v) { return eval('(' + v + ')'); },
        //转为日期格式
        parseDate: function (v) { return Date.parse(new Date(v.replace(/-/g, "/"))); },
        //转为金钱格式
        parseMoney: function (v) { if ("string" == typeof v) { v = Number(v) }; return v.toFixed(2) },
        //获取审核手续费
        getCommission: function (v) { v = Number("" + v); var re = (v * 0.03).toFixed(2); return Number(re) },
        //银行卡号 每四位 一个空格
        getSpaceBankCode: function(v) { return (v + "").replace(/\s/g, '').replace(/(.{4})/g, "$1 ") },
        // 周星驰  —>  **驰
        getStarName: function(v) { return v.replace(v.charAt(1),"*")}, 
        getStarName1: function(name) {
            var star = "", len = name.length - 1
            var last = name.slice(name.length-1)
            for(var i = 0;i<len;i++) {
                    star += "*"
            }
            return star + last
        },
        // 6228480078809886479 -> 622*************479
        getStarBankNo: function(v) { return (v + "").replace(/^(.{4}).*(.{3})$/,"$1 **** **** *$2") },
        getStarID: function(v) { return (v + "").replace(/^(.{3}).*(.{3})$/,"$1************$2") },
        getStarPhone: function(v) { return (v + "").replace(/^(.{3}).*(.{3})$/,"$1*****$2") },
        //字母随机数
        getRandom: function() { return (Math.random() / +new Date()).toString(36).replace(/\d/g, '').slice(1)}
    }
})();

var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
            qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
    }(),
    language:(navigator.browserLanguage || navigator.language).toLowerCase()
}

/**
* 用户
*/
var userUtil = (function (global) {
    return {
        sid: function (v) {
            if (undefined == v) {
                return global.storage.get("sid");
            } else if (v) {
                global.storage.set("sid", v);
            } else {
                global.storage.clear("sid");
            }
        },
        userID: function (v) {
            if (undefined == v) {
                return global.storage.get("userID");
            } else if (v) {
                global.storage.set("userID", v);
                global.storage.set("userID_Time", Date.parse(new Date()));
            } else {
                global.storage.clear("userID");
            }
        },
        mobile: function (v) {
            if (undefined == v) {
                return global.storage.get("mobile");
            } else if (v) {
                global.storage.set("mobile", v);
            } else {
                global.storage.clear("mobile");
            }
        },
        autoLogin: function (obj) {
            var conf = {
                async: true,
                success: function () { },
                unregist: function () {
                    layer.hideLoad();
                    layer.alert({
                        content: global.unregistered,
                        btnText: "马上去注册",
                        btnEvent: function () { window.location.href = global.registUrl }
                    });
                },
                error: function () {
                    layer.hideLoad();
                    layer.alert(global.loginTimeout);
                }
            };
            $.extend(conf, obj);

            var _user = userUtil;
            var _openid = _user.openID();
            if (_openid) {
                $.ajax({
                    url: global.localUrl + "order/user/loginByOpenId.json",
                    type: "post",
                    data: {
                        openId: _openid,
                        ss: new Date().getMilliseconds()
                    },
                    async: conf.async,
                    success: function (re) {
                        if (0 == re.code) {
                            _user.userID(re.result.sessionId);
                            global.storage.set("mobile", re.result.mobileNumber);
                            global.storage.set("userCardID", re.result.userCardID);
                            global.storage.set("userRealName", re.result.userRealName);
                            conf.success();
                        } else if (100103 == re.code) {
                            conf.unregist();
                        } else {
                            conf.error();
                        }
                    },
                    error: function (e) {
                        conf.error();
                    }
                });
            } else {
                conf.error();
            }
        },
        ajax: function (obj) {
            var _this = this;
            var param = {
                url: "",
                type: "post",
                data: {},
                success: _success,
                fault: false, //是否允许有 容错能力
                error: function () {
                    layer.hideLoad();
                    layer.tips(global.serverError);
                },
                autoLogin: true,
                done: function (re) { },
                fail: function (re) {
                    layer.hideLoad();
                    layer.tips(re.message);
                },
                nologin: function () {
                    layer.hideLoad();
                    layer.tips(global.loginTimeout);
                },
                unregist: null
            };
            $.extend(param, obj);
            if(_this.sid()) {
                param.data.sessionId = _this.sid();
            }
            _ajax();

            function _ajax() {
                $.ajax({
                    url: param.url,
                    type: param.type,
                    data: JSON.stringify(param.data),
                    success: param.success,
                    error: param.error,
                    contentType: 'application/json;charset=utf-8'
                });
            }

            function _success(re) {
                if (1 == re.code) {
                    param.done(re);
                } else if (1000 == re.code) {
                    //未登录
                    _this.sid('');
                    _this.userID('');
                    _this.mobile('');
                    sessionStorage.removeItem('isOverdue');
                    window.location.href="../user/login.html";
                } else {
                    if(!param.fault) {
                        param.fail(re);
                    } else {
                        param.done(re);
                    }
                    
                }
            }
        }
    }
})(global);


/**
* 布局
*/
var layer = (function () {
    var _tips_timeout;
    return {
        /**
        * 加载中
        */
        showLoad: function () {
            if ($(".layer_load").length == 0) {
                $("body").append("<div class='layer_load'><div class='layer_mask'></div><i class='layer_load_icon icon-loading'></i></div>");
            }
            $(".layer_load").addClass("on");
        },
        hideLoad: function () {
            $(".layer_load").removeClass("on");
        },
        /**
        * Alert 
        */
        alert: function (obj) {
            var conf = {
                title: "提 示",
                content: "",
                btnText: "确 定",
                btnEvent: function () { }
            };
            if (typeof obj == "string") { obj = { content: obj } };
            $.extend(conf, obj);
            if ($(".alert").length == 0) {
                $("body").append("<div class='layer_dialog alert'><div class='layer_mask'></div><div class='layer_dialog_box'><div class='layer_dialog_hd'><span class='layer_dialog_title'></span><i class='layer_btn_close icon-close' style='display:none'></i></div><div class='layer_dialog_cn'></div><div class='layer_dialog_ft'><a class='layer_btn layer_btn_primary'></a></div></div></div>");
            }
            $(".alert").addClass("on");
            $(".alert .layer_dialog_title").text(conf.title);
            $(".alert .layer_dialog_cn").html(conf.content);
            $(".alert .layer_btn").text(conf.btnText).off("click").on("click", function () { conf.btnEvent(); close(); });
            $(".alert .layer_btn_close").off("click").on("click", function () { conf.btnEvent(); close(); });

            function close() {
                $(".alert").removeClass("on");
            }
        },
        /**
        * Confirm 
        */
        confirm: function (obj) {
            var conf = {
                title: "提 示",
                content: "",
                btnOKText: "确 定",
                btnCancelText: "取 消",
                btnOKEvent: function () { },
                btnCancelEvent: function () { }
            };
            $.extend(conf, obj);
            if ($(".confirm").length == 0) {
                $("body").append("<div class='layer_dialog confirm'><div class='layer_mask'></div><div class='layer_dialog_box'><div class='layer_dialog_hd'><span class='layer_dialog_title'></span><i class='layer_btn_close icon-close' style='display:none'></i></div><div class='layer_dialog_cn'></div><div class='layer_dialog_ft'><a class='layer_btn'></a><a class='layer_btn layer_btn_primary'></a></div></div></div>");
            }
            $(".confirm").addClass("on");
            $(".confirm .layer_dialog_title").text(conf.title);
            $(".confirm .layer_dialog_cn").html(conf.content);
            $(".confirm .layer_btn").eq(0).text(conf.btnCancelText).off("click").on("click", function () { conf.btnCancelEvent(); close(); });
            $(".confirm .layer_btn").eq(1).text(conf.btnOKText).off("click").on("click", function () { conf.btnOKEvent(); close(); });
            $(".confirm .layer_btn_close").off("click").on("click", function () { conf.btnCancelEvent(); close(); });

            function close() {
                $(".confirm").removeClass("on");
            }
        },
        /**
        * Tips 
        */
        tips: function (obj) {
            var conf = {
                content: "",
                timeout: 2,
                fn: function () { }  //此回掉不安全 不要放逻辑代码
            }
            if (typeof obj == "string") { obj = { content: obj } };
            $.extend(conf, obj);
            if ($(".layer_tips").length == 0) {
                $("body").append("<div class='layer_tips'><p class='layer_tips_cn'></p></div>");
            }
            var $tips = $(".layer_tips");
            $tips.addClass("on").find(".layer_tips_cn").html(conf.content);

            if (_tips_timeout) {
                clearTimeout(_tips_timeout);
            }
            _tips_timeout = setTimeout(function () { conf.fn(); $tips.removeClass("on"); }, conf.timeout * 1000);
        },
        /**
        * Iframe 
        */
        iframe: function (obj) {
            var conf = {
                url: "",
                close: function () { }
            }
            if (typeof obj == "string") { obj = { url: obj } };
            $.extend(conf, obj);
            if ($(".iframe").length == 0) {
                $("body").append("<div class='layer_dialog iframe'><div class='layer_mask'></div><div class='layer_dialog_page'><i class='layer_btn_close icon-close'></i><div class='layer_dialog_iframe'></div></div>");
            }
            $(".iframe").addClass("on");
            $(".iframe .layer_dialog_iframe").empty().load(conf.url);
            $(".iframe .layer_btn_close").off("click").on("click", function () { conf.close(); close(); });

            function close() {
                $(".iframe").removeClass("on");
            }
        }

    }
})();

 //rem布局
!(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
          var clientWidth = docEl.clientWidth;
          if (!clientWidth) return;

        if (!navigator.userAgent.match(/(iPhone|iPad|iPod|Android|ios|webOS|BlackBerry)/i)) {
                docEl.style.fontSize = '110px';
        }else{
            docEl.style.fontSize = 100 * (clientWidth / 375) + 'px';
        }
        };
        if (!doc.addEventListener) return;
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);


/**
* Init
*/
!function (window) {
    /* 关闭提醒 */
    $(".remind .remind_hide").on("click", function () {
        $(this).parents(".remind").hide();
    })

    /* 文本框清空 */
    $(".cell.input .txt").on("focus keyup", function () {
        var $this = $(this);
        if ($.trim($this.val()).length > 0) {
            $this.parents(".cell").find(".btn_empty").css({ "visibility": "visible" });
        }
    });

    $(".cell.input .txt").on("blur", function () {
        var $this = $(this);
        setTimeout(function () {
            $this.parents(".cell").find(".btn_empty").css({ "visibility": "hidden" });
        }, 1);
    });

    $(".cell.input .btn_empty").on("click", function () {
        $(this).parents(".cell").find(".txt").val("");
    });

    /* 模态框关闭 */
    $(".layer_dialog .layer_btn_close").on("click", function () {
        $(this).parents(".layer_dialog").removeClass("on");
    })
}(window);

